package edu.washington.ling.syntric.proc;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import org.kohsuke.args4j.*;

import edu.washington.ling.syntric.io.TreeFileReader;
import edu.washington.ling.syntric.io.TreeFileWriter;
import edu.washington.ling.syntric.io.TreeReader;
import edu.washington.ling.syntric.io.TreeRepresentation;
import edu.washington.ling.syntric.io.TreeWriter;
import edu.washington.ling.syntric.struct.error.PrintingExceptionHandler;
import edu.washington.ling.syntric.struct.error.UnreadableRepresentationException;
import edu.washington.ling.syntric.struct.tree.Tree;


public class ConvertFormat {

	private static PrintingExceptionHandler pHandler = new PrintingExceptionHandler();
	private static ConvertFormatOptions opts = new ConvertFormatOptions();
	
	private static void convertInputFile() {
		int numConverted = 0;
		int numTrees = 0;
		
		try {
			TreeFileReader tfr = TreeFileReader.newReader(opts.inputFilePath, opts.inputFileFormat, opts.inputTreeType);
			TreeFileWriter tfw = TreeFileWriter.newWriter(opts.outputFilePath, opts.outputFileFormat);
			TreeReader tr = TreeReader.newReader(opts.inputTreeFormat);
			TreeWriter tw = TreeWriter.newWriter(opts.outputTreeFormat);
			
			List<String> ids = new LinkedList<String>(tfr.getIDs());
			Collections.sort(ids);
			for (String id: ids) {
				TreeRepresentation rep = tfr.readTreeRepWithID(id);
				try {
					Tree t = tr.readTree(rep);
					tfw.writeTreeRep(tw.writeTree(t), id);
					numConverted++;
				}
				catch (UnreadableRepresentationException e) {
					pHandler.handle(e, "could not process representation.");
				}
				finally {
					numTrees++;
				}
			}
			tfw.close();
		}
		catch (Exception e) {
			e.printStackTrace();
			pHandler.handle(e, "format conversion failed.");
			System.exit(1);
		}
		System.out.println("Format conversion was successful.");
		System.out.println(String.format("%d/%d trees were successfully converted.", numConverted, numTrees));
	}
	
	
	public static void main(String[] args) {
		CmdLineParser parser = new CmdLineParser(opts);
		try {
			parser.parseArgument(args);
			convertInputFile();
		}
		catch(CmdLineException e) {
			System.err.println(e.getMessage());
			System.err.print("ConvertFormat");
			parser.printSingleLineUsage(System.err);
			System.err.println();
			parser.printUsage(System.err);
			System.exit(1);
		}
	}
}
